package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemetia.WemetiaConstants;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @作者 itcast
 * @创建日期 2020/9/23 17:39
 **/
@Service
@Log4j2
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FastDFSClient fastDFSClient;

    @Value("${fdfs.url}")
    String fileServerUrl; // 图片服务器路径

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1 检查参数
        if(multipartFile == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 上传图片到fastdfs
        String filePath = null;
        try {
            filePath = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 获取当前登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        // 3. 保存素材信息到wm_material表
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setUrl(filePath);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial); // 素材信息保存到数据库
        // 拼接图片路径 并返回素材信息到前台
        wmMaterial.setUrl(fileServerUrl + filePath);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto wmMaterialDto) {
        //1. 检查参数
        if(wmMaterialDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmMaterialDto.checkParam();
        //2. 查询素材列表
        //2.1 封装分页条件
        IPage<WmMaterial> pageParam = new Page<>(wmMaterialDto.getPage(),wmMaterialDto.getSize());
        //2.2 封装查询条件
        Integer userId = WmThreadLocalUtils.getUser().getId();
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmMaterial::getUserId,userId);
        // 是否收藏
        Short isCollected = wmMaterialDto.getIsCollection();
        if(isCollected!=null && isCollected == WemetiaConstants.IS_COLLECT){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,isCollected);
        }
        IPage<WmMaterial> result = page(pageParam, lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(
                wmMaterialDto.getPage(),wmMaterialDto.getSize(),result.getTotal()
        );
        // 需要将url路径加上前缀
        List<WmMaterial> datas = result.getRecords();
        datas.stream().map((item)-> {
            item.setUrl(fileServerUrl + item.getUrl());
            return item;
        }).collect(Collectors.toList());
        responseResult.setData(datas);
        return responseResult;
    }

    @Autowired
    WmNewsMaterialMapper wmNewMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        //1. 检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 根据ID查询素材是否存在
        WmMaterial material = getById(id);
        if(material == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3. 存在素材，判断素材是否有引用
        Integer count = wmNewMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if(count > 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"素材已被引用");
        }
        //4. 没有引用 则先从fastdfs中删除对应图片
        fastDFSClient.delFile(material.getUrl());
        //5. 删除图片后， 删除素材数据
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 更新状态
        Integer userId = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,userId));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
